package model

import (
	"log"
	"time"
)

// 地址表，一个客户可能有多个地址
type Address struct {
	Id         int64
	CustomerId int64     // 客户 ID
	PostCode   string    `xorm:"notnull default('000000')"` // 邮政编码
	Address    string    `xorm:"notnull"`                   // 地址
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
}

type AddressResult struct {
	Id        int64  `json:"id"`
	PostCode  string `json:"post_code"`
	Address   string `json:"address"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

func (a *Address) Create() error {
	_, err := GetDB().Insert(a)
	if err != nil {
		log.Printf("创建地址失败：%v", err)
		return err
	}
	return nil
}

func (a *Address) DeleteMulti(ids []int) error {
	_, err := GetDB().In("id", ids).Delete(a)
	if err != nil {
		log.Printf("[db 删除地址] failed: %v", err)
		return err
	}
	return nil
}

func (a *Address) Update() error {
	_, err := GetDB().Table(a).ID(a.Id).Update(map[string]interface{}{
		"address": a.Address,
	})
	if err != nil {
		log.Printf("[db 更新地址信息] failed: %v", err)
		return err
	}
	return nil
}

func (a *Address) Query(query string, pn, ps int) ([]AddressResult, int, error) {
	x := GetDB()
	var results []Address
	total, err := x.Count(a)
	if err != nil {
		log.Printf("[db 查询地址] failed: %v", err)
		return nil, 0, err
	}
	err = x.OrderBy("id DESC").Limit(ps, (pn-1)*ps).Find(&results)
	if err != nil {
		log.Printf("[db 查询地址] failed: %v", err)
		return nil, 0, err
	}
	var r []AddressResult
	for _, v := range results {
		r = append(r, AddressResult{
			Id:        v.Id,
			PostCode:  v.PostCode,
			Address:   v.Address,
			CreatedAt: v.CreatedAt.Unix(),
			UpdatedAt: v.UpdatedAt.Unix(),
		})
	}
	return r, int(total), nil
}

//func (a *Address) CreateMulti(address []Address) (int64, error) {
//	// 批量添加
//	x := GetDB()
//	affected, err := x.Insert(address)
//	if err != nil {
//		log.Printf("创建 address 失败：%v", err)
//		return affected, err
//	}
//	return affected, nil
//}
